import Router from 'vue-router'
import Vue from 'vue'
import pageList from "./pageList";

Vue.use(Router);

// 定义routes,最终封装的所有router
let routes = [];
let defaultPage = '';
// 获取路由对象 name,about这些..
let pageNames = Object.keys(pageList);
// 抽离出来push路由的函数
const pustRoute = (name, component) => {
    routes.push({
        path: `/${name}`,
        name: name,
        component: component
    })
};

// 循环对象
pageNames.forEach((name, index) => {
    // 存储pageName的变量,用来给defaultName赋值
    let pageName;
    // name代表当前对象,index对象索引,判断当前对象是否有子节点
    if (pageList[name].subPages) {
        let subPageNames = Object.keys(pageList[name].subPages);
        let subPages = pageList[name].subPages;
        subPageNames.forEach((name, index) => {
            (index === 0) && (pageName = name);
            pustRoute(name, subPages[name].component)
        })
    } else {
        // routes.push({
        //     path: `/${name}`,
        //     name: name,
        //     component: pageList[name].component
        // })
        (index === 0) && (pageName = name); // 如果index等于0 把name赋值给pageName
        pustRoute(name, pageList[name].component)
    }
    (index === 0) && (defaultPage = pageName)
});

// 添加/跳转到home  404和无效页面
routes.push({
        path: '/',
        redirect: `/${defaultPage}`
    },
    {
        path: '*',
        component: () => import('@/pages/NotFound.vue')
    },
    {
        path: '/404',
        name: "404",
        meta: {title: 'Not Found'},
        component: () => import('@/pages/NotFound.vue')
    }
);

// const vueRouter = [
//     {path: '/', redirect: '/home'},
//     {
//         path: '/home',
//         name: 'home',
//         redirect: '/main',
//         component: () => import('@/pages/Home'),
//         children: [
//             {path: '/main', component: () => import('@/pages/Mainpage')},
//             {path: '/message', component: () => import('@/pages/Message')},
//             {path: '/about', component: () => import('@/pages/About')},
//             {path: '/more', component: () => import('@/pages/Other')},
//             {path: '/setting', component: () => import('@/pages/Setting')},
//         ]
//     },
// ];

export default new Router({
        //mode:'history', //路由模式:默认为hash,如果改为history,则需要后端进行配合
        //base:'/',//基路径:默认值为'/'.如果整个单页应用在/moduleA/下,base就应该设为'/moduleA/'.一般可以写成__dirname,在webpack中配置.
        mode: 'history',
        routes: routes
    }
)
